#!/bin/bash

set -e

ZIPALIGN="/opt/android-sdk/build-tools/26.0.1/zipalign"
APKSIGNER="/opt/android-sdk/build-tools/26.0.1/apksigner" # /!\ version 26

PRO_ROOT=`pwd`
KEY_STORE_FILE=$PRO_ROOT/keystore/release-key.jks

FIRST_OUT_APK=$PRO_ROOT/app/build/outputs/apk/release/app-release-unsigned.apk
APKSIGNED_APK=$PRO_ROOT/release/app-unsigned-aligned.apk
UNSIGNED_APK=$PRO_ROOT/release/app-unsigned-aligned.apk
RELEASE_APK=$PRO_ROOT/release/app-release.apk

STOREPASS=123QWE
KEYPASS=$STOREPASS
DNAME=TEST
CN=TEST
OU=TEST
O=TEST
L=TEST
ST=TEST
C=TEST


if [ ! -d $PRO_ROOT/release ] ;then
	echo "Creating release folder..."
	mkdir $PRO_ROOT/release
fi

if [ ! -d $PRO_ROOT/keystore ] ;then
	echo "Creating keystore folder..."
	mkdir $PRO_ROOT/keystore
fi

echo "Cleaning..."
rm -rf 	$PRO_ROOT/app/build/outputs/apk/*
rm -rf $APKSIGNED_APK
rm -rf $UNSIGNED_APK
rm -rf $RELEASE_APK
rm -rf release-key.jks

if [ ! -f "$KEY_STORE_FILE" ]; then
	echo "Generating app-release-key.jks file..."
	keytool -genkey -v -keystore $KEY_STORE_FILE -keyalg RSA -keysize 2048 -validity 10000 -alias my-alias -storepass $STOREPASS -keypass $KEYPASS -dname CN=$CN,OU=$OU,O=$O,L=$L,ST=$ST,C=$C
fi

echo "Making APK..."
./gradlew assembleRelease


echo "Aligning APK..."
$ZIPALIGN -v -p 4 $FIRST_OUT_APK $APKSIGNED_APK

cp $KEY_STORE_FILE ./
echo "Signing APK..."
$APKSIGNER sign --ks release-key.jks --ks-pass pass:$KEYPASS --out $RELEASE_APK $UNSIGNED_APK

echo "Verify APK is Signed..."

$APKSIGNER verify $RELEASE_APK


#if [ "$1" == "test" ]; then
#	echo "Launching..."
#	adb install -r bin/hello.apk
#	adb shell am start -n com.example.helloandroid/.MainActivity
#fi
